import 'package:flutter/material.dart';
import 'package:happy_elf_app/utils/adaption.dart';
import 'package:happy_elf_app/utils/color.dart';
import 'package:speech_to_text/speech_recognition_result.dart';
import 'package:speech_to_text/speech_to_text.dart';

class Space extends StatefulWidget {
  const Space({super.key});

  @override
  State<Space> createState() => _SpaceState();
}

class _SpaceState extends State<Space> with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  // 语音识别核心变量
  final SpeechToText _speechToText = SpeechToText();
  bool _isSpeechAvailable = false; // 语音识别是否可用
  bool _isRecording = false; // 是否正在录音（控制按钮状态）
  String _realTimeText = "点击下方按钮并长按，开始语音输入..."; // 实时识别文字

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this);
    _initSpeechRecognition(); // 初始化语音识别
  }

  @override
  void dispose() {
    _controller.dispose();
    _speechToText.stop(); // 销毁时停止录音
    super.dispose();
  }

  /// 初始化语音识别（检查设备支持性、获取权限）
  void _initSpeechRecognition() async {
    bool available = await _speechToText.initialize(
      onStatus: (status) {
        // 录音状态变化：如停止、超时等
        if (status == "notListening") {
          setState(() => _isRecording = false);
        }
      },
      onError: (error) {
        // 识别错误提示
        setState(() {
          _realTimeText = "识别出错：${error.errorMsg}";
          _isRecording = false;
        });
      },
    );
    setState(() => _isSpeechAvailable = available);
  }

  /// 开始录音（长按触发）
  void _startRecording() async {
    if (!_isSpeechAvailable) {
      setState(() => _realTimeText = "语音识别不可用，请检查设备设置");
      return;
    }

    setState(() {
      _isRecording = true;
      _realTimeText = "正在聆听...";
    });

    // 开始监听语音，实时返回结果
    await _speechToText.listen(
      onResult: _onRealTimeResult, // 实时结果回调
      localeId: "zh_CN", // 中文识别
      partialResults: true, // 支持实时返回部分识别结果
      listenFor: const Duration(seconds: 30), // 最长录音30秒
    );
  }

  /// 停止录音（松开长按触发）
  void _stopRecording() async {
    await _speechToText.stop();
    setState(() => _isRecording = false);
    // 若识别结果为空，提示用户
    if (_realTimeText == "正在聆听...") {
      setState(() => _realTimeText = "未识别到语音，请重新尝试");
    }
  }

  /// 实时识别结果回调
  void _onRealTimeResult(SpeechRecognitionResult result) {
    setState(() {
      // 更新实时识别文字，支持连续识别（拼接结果）
      _realTimeText = result.recognizedWords;
    });
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Container(
      width: 375.px,
      height: size.height,
      padding: EdgeInsets.only(bottom: 80.px),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          // 页面标题
          Padding(
            padding: EdgeInsets.only(top: 40.px, bottom: 60.px),
            child: Text(
              '精灵空间',
              style: TextStyle(fontSize: 20.px, color: hexColor('#000')),
            ),
          ),

          // 实时识别文字显示区域（占页面主要空间）
          Expanded(
            child: Container(
              width: 320.px,
              padding: EdgeInsets.all(20.px),
              decoration: BoxDecoration(
                color: hexColor('#F5F5F5'),
                borderRadius: BorderRadius.circular(16.px),
                boxShadow: [
                  BoxShadow(
                    color: hexColor('#00000010'),
                    blurRadius: 8.px,
                    spreadRadius: 2.px,
                  )
                ],
              ),
              child: SingleChildScrollView(
                child: Text(
                  _realTimeText,
                  style: TextStyle(
                    fontSize: 16.px,
                    color: hexColor('#333'),
                    height: 1.5,
                  ),
                ),
              ),
            ),
          ),

          // 长按语音按钮（底部固定）
          Padding(
            padding: EdgeInsets.only(top: 40.px),
            child: GestureDetector(
              onLongPressStart: (_) => _startRecording(), // 长按开始
              onLongPressEnd: (_) => _stopRecording(), // 松开停止
              child: Container(
                width: 60.px,
                height: 60.px,
                decoration: BoxDecoration(
                  color:
                      _isRecording ? hexColor('#F04136') : hexColor('#4A90E2'),
                  shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      color: _isRecording
                          ? hexColor('#F04136')
                          : hexColor('#4A90E0'),
                      blurRadius: 10.px,
                      spreadRadius: 3.px,
                    )
                  ],
                ),
                child: Icon(
                  Icons.mic,
                  color: Colors.white,
                  size: 30.px,
                ),
              ),
            ),
          ),

          // 按钮提示文字
          Padding(
            padding: EdgeInsets.only(top: 12.px),
            child: Text(
              _isRecording ? "松开停止录音" : "长按开始语音输入",
              style: TextStyle(
                fontSize: 14.px,
                color: hexColor('#666'),
              ),
            ),
          )
        ],
      ),
    );
  }
}
